<template>
    <div class="page-wrap" v-loading="loading">
        <div v-if="detailData.id" class="page-cont">
            <a-page-header @back="handleBack">
                <template #subTitle>
                    <span>{{ $filters.valToNameFilter('fromSystem', detailData.system) }}</span>
                </template>
                <div class="header-title">
                    {{ detailData.title }}
                </div>
            </a-page-header>
            <template v-for="(item, index) of comps" :key="index">
                <div v-if="item.show">
                    <a-divider style="margin: 0" v-if="index !== 0" />
                    <component :ref="setComItemRef(item)" :is="item.comName" :detail="detailData" :disabled="item.disabled" @save="handleSave" @success="getDetailData" @detailChange="detailChange" />
                </div>
            </template>
        </div>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { message } from 'ant-design-vue';
import BaseInfo from '@/views/requireChange/changeDetail/components/BaseInfo.vue';
import ChangeInfluence from '@/views/requireChange/changeDetail/components/ChangeInfluence.vue';
import ChangePlan from '@/views/requireChange/changeDetail/components/ChangePlan/index.vue';
import AuditOpinion from '@/views/requireChange/changeDetail/components/AuditOpinion.vue';
import HistoryRecord from '@/views/requireChange/changeDetail/components/HistoryRecord/index.vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import store from '@/store';
import { defineComponent, unref, reactive, toRefs } from 'vue';
export default defineComponent({
    name: 'ChangeDetail',
    components: {
        BaseInfo,
        ChangeInfluence,
        ChangePlan,
        AuditOpinion,
        HistoryRecord
    },
    setup() {
        const { route, handleBack } = useRouterApi({
            backQuery: {
                path: '/requireChange/requireChangeList'
            }
        });
        const state = reactive<any>({
            comps: [],
            detailData: {},
            loading: false,
            form: {}
        });
        const comItemRefs: any = reactive({});
        const setComItemRef = (item) => (el) => {
            comItemRefs[item.comName] = el;
        };
        const getDetailData = async () => {
            state.loading = true;
            const query = {
                id: route.query.id
            };
            const { success, moule } = await api.requireChangeModel.findById(query);
            state.loading = false;
            if (success) {
                state.detailData = { ...moule, changePlan: moule.changePlan ? JSON.parse(moule.changePlan) : null };
                initComps();
            }
        };
        const initComps = () => {
            const allComps = [
                {
                    comName: 'BaseInfo',
                    disabled: false, //1.没有可操作版本 2.非系统负责人 3.团队长审批之后的节点 4.历史查看详情
                    show: true
                },
                {
                    comName: 'ChangeInfluence',
                    disabled: false,
                    show: true
                },
                {
                    comName: 'ChangePlan',
                    disabled: false, // 1.团队长审批之后的节点 2.历史查看详情
                    show: true // 1.没有可操作版本 2.不是系统负责人
                },
                {
                    comName: 'AuditOpinion',
                    disabled: false, // 1.结束流程 2.历史查看详情
                    show: true // 1.没有可操作版本 2.不是系统负责人
                },
                {
                    comName: 'HistoryRecord',
                    disabled: false,
                    show: true
                }
            ];
            state.comps = allComps.map((item) => ({
                show: checkIsShow(item),
                disabled: checkIsDisabled(item),
                comName: item.comName
            }));
        };
        // 检测模块是否显示
        const checkIsShow = ({ comName }) => {
            if (+state.detailData.status <= 2) {
                if (['AuditOpinion', 'ChangePlan'].includes(comName)) {
                    // 判断有没有可操作的版本，因为最开始影响的版本的状态可能为已废弃
                    if (state.detailData.versionDTOS && state.detailData.versionDTOS.length) {
                        // 判断当前操作人是不是该系统负责人
                        return state.detailData.agentUser.includes(store.getters.userInfo.employeeDTO.empId);
                    }
                    // 没有可操作版本，不显示对应模块
                    else {
                        return false;
                    }
                } else {
                    return true;
                }
            } else {
                return true;
            }
        };
        // 检测模块是否可编辑
        const checkIsDisabled = ({ comName }) => {
            if (+state.detailData.status <= 2) {
                // 判断有没有可操作的版本，因为最开始影响的版本的状态可能为已废弃
                if (state.detailData.versionDTOS && state.detailData.versionDTOS.length) {
                    // 判断当前操作人是不是该系统负责人
                    return !state.detailData.agentUser.includes(store.getters.userInfo.employeeDTO.empId);
                } else {
                    return true;
                }
            } else {
                if (state.detailData.status === '5') {
                    return true;
                }
                return comName !== 'AuditOpinion';
            }
        };
        // 检测是否填入
        const validateAllForm = async (validateComps: string[]) => {
            let res = false;
            for (let i = 0; i < validateComps.length; i++) {
                const name = validateComps[i];
                const target = unref(comItemRefs[name]);
                res = await target.validate();
                if (res) {
                    if (target.form) {
                        state.form = {
                            ...state.form,
                            ...target.form
                        };
                    }
                } else {
                    return res;
                }
            }
            return res;
        };
        const handleSave = async (type: number) => {
            //type等于1表示暂存
            const request = type === 1 ? api.requireChangeModel.save : api.requireChangeModel.auditProcess;
            const res = await validateAllForm(['BaseInfo', 'ChangePlan', 'AuditOpinion']);
            if (res) {
                state.loading = true;
                const query = {
                    ...state.detailData,
                    ...state.form,
                    changeInfluence: JSON.stringify(state.detailData.versionDTOS)
                };
                query.changePlan = JSON.stringify(query.changePlan);
                // console.log(query);
                const { success, errorMsg } = await request(query);
                if (success) {
                    message.success('操作成功');
                    handleBack(); // 返回上一个界面
                } else {
                    message.error(errorMsg);
                }
                state.loading = false;
            } else {
                message.error('请填写所有必填项');
            }
        };
        const detailChange = (data) => {
            state.detailData = {
                ...state.detailData,
                ...data
            };
        };
        getDetailData();
        return {
            ...toRefs(state),
            detailChange,
            setComItemRef,
            handleSave,
            getDetailData,
            handleBack
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    position: relative;
    height: 100%;
    .header-title {
        font-size: 20px;
        color: @title-font-color;
        font-weight: bold;
    }
    .page-cont {
        margin-top: 22px;
        position: relative;
        background: #fff;
    }
}
</style>